/*
 * Copyright 2002-2013 Edward L. Stauff.                  Contact: <EdStauff@gmail.com>.
 * 
 * This file, "NumUtils.cs", is part of the "Stauffware.Common" class library.
 * "Stauffware.Common" is free software: you can redistribute it and/or 
 * modify it under the terms of the GNU Lesser Public License as published by the 
 * Free Software Foundation, either version 3 of the License, or (at your option) 
 * any later version.
 * 
 * "Stauffware.Common" is distributed in the hope that it will be useful, 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser Public License for more 
 * details.
 * 
 * You should have received a copy of the GNU Lesser Public License along with 
 * "Stauffware.Common".  If not, see <http://www.gnu.org/licenses/>.
 */

using System;
using System.Collections.Generic;
using System.Text;

namespace Stauffware.Common.Core
{
	/// <summary>
	/// Utilities for dealing with numbers.
	/// </summary>
	public static class NumUtils
	{
		//-----------------------------------------------------------------------------
		/// <summary>
		/// Converts an integer to a string, using specified digit characters.
		/// </summary>
		/// <param name="n">the value to be converted</param>
		/// <param name="digits">the digits; the radix is implied by the length of the string</param>

		public static string ToString (int n, string digits)
		{
			Require.Condition(digits.Length > 1);
			int radix = digits.Length;

			bool negative = n < 0;
			if (negative) n = -n;
			string output = "";
			
			while (n != 0)
			{
				output = digits[n % radix] + output;
				n = n / radix;
			}

			if (output == "")
				output += digits[0];
			else if (negative)
				output = "-" + output;

			return output;
		}

		//-----------------------------------------------------------------------------
		/// <summary>
		/// Converts an integer to a string, using specified digit characters.
		/// </summary>
		/// <param name="n">the value to be converted</param>
		/// <param name="digits">the digits; the radix is implied by the length of the string</param>

		public static string ToString (long n, string digits)
		{
			Require.Condition(digits.Length > 1);
			int radix = digits.Length;

			bool negative = n < 0;
			if (negative) n = -n;
			string output = "";

			while (n != 0)
			{
				output = digits[(int)(n % radix)] + output;
				n = n / radix;
			}

			if (output == "")
				output += digits[0];
			else if (negative)
				output = "-" + output;

			return output;
		}

	}
}
